//
//  SHDiscoverSearchView.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/23.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit

class SHDiscoverSearchView: UIView {

    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, SCREENW, 35))
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func buttonClick(){
        
        self.textfield.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textfield.resignFirstResponder()
        }
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor.purpleColor()
        
        
        addSubview(cancelButton)
        
        addSubview(textfield)
        
        cancelButton.snp_makeConstraints { (make) -> Void in
            make.top.bottom.trailing.equalTo(self)
            make.width.equalTo(50)
        }
        
        textfield.snp_makeConstraints { (make) -> Void in
            make.top.leading.bottom.equalTo(self)
            
            make.trailing.equalTo(self)
        }
        
    }
    
    private lazy var cancelButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setTitle("取消", forState: UIControlState.Normal)
        
        button.setTitleColor(ThemeColor, forState: UIControlState.Normal)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        button.sizeToFit()
        
        return button
        
    }()
    
    
    private lazy var textfield: UITextField = {
        
        let img = UIImageView(imgName: "searchbar_textfield_search_icon")
        
        img.contentMode = .Center
        
        img.frame.size = CGSize(width: 35, height: 35)
        
        let textfield = UITextField()
        
        textfield.placeholder = "上海传智播客3期"
        
        textfield.textAlignment = .Center
        
        textfield.layer.borderColor = ThemeColor.CGColor
        
        textfield.layer.borderWidth = 2
        
        textfield.backgroundColor = UIColor.whiteColor()
        
        textfield.leftView = img
        textfield.leftViewMode = .Always
        
        textfield.delegate = self

        return textfield
        
    }()
}

extension SHDiscoverSearchView: UITextFieldDelegate{
    
    func textFieldDidBeginEditing(textField: UITextField) {
        self.textfield.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self).offset(-50)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
}
